#include "head.hpp"
static const uint16_t port = 8080;
int main(int argc, char *argv[])
{
    int clientfd = socket(AF_INET, SOCK_STREAM, 0);
    ERROR_CHECK(clientfd, -1, "socket");
    struct sockaddr_in serveraddr;
    memset(&serveraddr, 0, sizeof(serveraddr));
    serveraddr.sin_family = AF_INET;
    serveraddr.sin_port = htons(port);
    serveraddr.sin_addr.s_addr = inet_addr("127.0.0.1");
    int ret = connect(clientfd, (struct sockaddr *)&serveraddr, sizeof(serveraddr));
    ERROR_CHECK(ret, -1, "connect");
    char filename[100] = {0};
    int len = 0;
    ret = recvn(clientfd, (char *)&len, sizeof(len));
    printf("ret: %d, filename's len:%d\n", ret, len);
    ret = recvn(clientfd, filename, len);
    printf("ret: %d, recv msg:%s\n", ret, filename);
    int wfd = open(filename, O_CREAT | O_RDWR, 0644);
    ERROR_CHECK(wfd, -1, "open");
    off_t length = 0;
    recvn(clientfd, (char *)&length, sizeof(length));
    printf("file length: %ld\n", length);
    off_t splice = length / 100;
    off_t currSize = 0;
    off_t lastSize = 0;
    char buff[1000] = {0};
    while (1)
    {
        ret = recvn(clientfd, (char *)&len, sizeof(len));
        if (ret == 0)
        {
            break;
        }
        ret = recvn(clientfd, buff, len);
        write(wfd, buff, ret);
        currSize += ret;
        if (currSize - lastSize > splice)
        {
            usleep(500000);
            printf("has complete %.2lf%%\r", (double)currSize / length * 100);
            fflush(stdout);
            lastSize = currSize;
        }
    }
    printf("has complete 100.00%%\n");
    close(wfd);
    close(clientfd);
    return 0;
}